#include <linux/completion.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/netdevice.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/mm_types.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/io.h>

#include <net/net_namespace.h>

#define err(msg) printk("%s failed\n", msg)

static char *buffer;

static int lv_open(struct inode *inodp, struct file *filp)
{
    buffer = kmalloc(PAGE_SIZE, GFP_KERNEL | __GFP_ZERO);
    if (!buffer)
        goto out;

    SetPageReserved(virt_to_page(buffer));
    return 0;
out:
    return -ENODEV;
}

static int lv_release(struct inode *inodp, struct file *filp)
{
    printk(KERN_INFO "buffer: %s\n", buffer);
    ClearPageReserved(virt_to_page(buffer));
    kfree(buffer);
    return 0;
}

static int lv_mmap(struct file *filp, struct vm_area_struct *vma)
{
    unsigned long start = vma->vm_start;
    unsigned long size = vma->vm_end - vma->vm_start;
    
    if (size != PAGE_SIZE)
        goto out;

    if (remap_pfn_range(vma, start, __pa(buffer) >> PAGE_SHIFT, PAGE_SIZE, PAGE_SHARED))
    {
        err("remap_pfn_range");
        goto out;
    }

    return 0;
out:
    return -ENOMEM;
}

static struct file_operations fops =
{
    .open     = lv_open,
    .release = lv_release,
    .mmap     = lv_mmap,
};

static int main_init(void)
{
    if (register_chrdev(150, "lv", &fops) < 0)
    {
        err("register_chrdev");
        goto out;
    }
    
    printk("char device register ok.\n");
    return 0;
out:
    return -ENODEV;
}

static void main_exit(void)
{
    unregister_chrdev(150, "lv");
    printk("char device unregister ok.\n");
}

module_init(main_init);
module_exit(main_exit);
MODULE_LICENSE("GPL");

